package com.opennetexam.manager.controller;

import com.opennetexam.manager.bussinessservice.ExamReportBusinessService;
import com.opennetexam.manager.common.CommonFunction;
import com.opennetexam.manager.common.OperationResult;
import com.opennetexam.manager.common.PageBean;
import com.opennetexam.manager.common.ReturnData;
import com.opennetexam.manager.databasemodel.FreeExamReport;
import com.opennetexam.manager.dto.*;
import com.opennetexam.manager.enums.DeploymentMode;
import com.opennetexam.manager.enums.ExamResultUploadState;
import com.opennetexam.manager.enums.OperationResultType;
import com.opennetexam.manager.enums.ParameterKey;
import com.opennetexam.manager.utils.Base64Util;
import com.opennetexam.manager.utils.FileUtil;
import com.opennetexam.manager.utils.GsonUtil;
import com.opennetexam.manager.utils.HttpRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author 奶茶
 * Created by on 2017/12/8.
 */
@Controller
@RequestMapping(value = "/ExamReport")
public class ExamReportController extends BaseController{

    @Autowired
    private ExamReportBusinessService examReportBusinessService;
    @Value("${ExamSiteURL}")
    private String examSiteURL;


    /**
     * 获取全部数据
     * @param requestBody
     * @param request
     * @param response
     */
    @RequestMapping(value = "/GetList",method = RequestMethod.POST)
    public void getList(@RequestBody Map<String,Object> requestBody, HttpServletRequest request, HttpServletResponse response){
        String account = (String) requestBody.get("account");
        ExamAdminInfoDTO adminUserInfo = getAdminUserInfo(account);
        //考试计划类别：0正式；1模拟
        Short planType = requestBody.get("planType") == null ? Short.valueOf("0") : Short.valueOf(String.valueOf(requestBody.get("planType")));

        List<ExamPlanViewModel> examPlanList = examReportBusinessService.findExamPlanList(adminUserInfo.getAppID(), adminUserInfo.getExamSiteID(), planType);
        CommonFunction.responseWrite(response,examPlanList);
    }


    //**************************************************统考情况********************************************************

    /**
     * 获取统考的考试结果列表
     * @param requestBody
     * @param request
     * @param response
     */
    @RequestMapping(value = "/GetExamReportList",method = RequestMethod.POST)
    public void getExamReportList(@RequestBody Map<String,Object> requestBody,HttpServletRequest request,HttpServletResponse response){
        String account = (String) requestBody.get("account");
        //考试计划ID
        String planId = (String) requestBody.get(ParameterKey.PLANID.getDisplay());
        //场次id
        String sceneId = (String) requestBody.get(ParameterKey.SCENEID.getDisplay());
        //考场id
        String roomId = (String) requestBody.get(ParameterKey.ROOMID.getDisplay());
        //科目id
        String subjectId = (String) requestBody.get(ParameterKey.SUBJECTID.getDisplay());
        //考生状态
        Integer statusId = (Integer) requestBody.get("statusId");

        List<ExamcaseViewModel> examReportList = examReportBusinessService.findExamReportList(planId, roomId, sceneId, subjectId, statusId, getAdminUserInfo(account).getAppID());
        CommonFunction.responseWrite(response,examReportList);

    }

    /**
     * 根据考场获取统考的考试明细列表
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/GetExamReportDetail",method = RequestMethod.POST)
    public void getExamReportDetail(@RequestBody Map<String,Object> requestBody, HttpServletResponse response){
        String account = (String) requestBody.get("account");
        ExamAdminInfoDTO adminUserInfo = getAdminUserInfo(account);
        String planId = (String) requestBody.get(ParameterKey.PLANID.getDisplay());
        String roomId = (String) requestBody.get(ParameterKey.ROOMID.getDisplay());
        String sceneId = (String) requestBody.get(ParameterKey.SCENEID.getDisplay());
        String subjectId = (String) requestBody.get(ParameterKey.SUBJECTID.getDisplay());

        List<ExamingMonitorViewModel> examingMonitorList = examReportBusinessService.findExamingMonitorList(planId, roomId, sceneId, subjectId, adminUserInfo.getAppID(), adminUserInfo.getExamSiteID(), adminUserInfo);
        CommonFunction.responseWrite(response,examingMonitorList);
    }


    /**
     * 导出统考报告
     * @param requestBody
     * @param request
     * @param response
     */
    @RequestMapping(value = "/ExamDownload",method = RequestMethod.POST)
    public void examDownload(@RequestBody Map<String,Object> requestBody,HttpServletRequest request,HttpServletResponse response) throws IOException {
        String account = (String) requestBody.get("account");
        ExamAdminInfoDTO adminUserInfo = getAdminUserInfo(account);
        List<Integer> reportIdList = GsonUtil.fromJsonToList(GsonUtil.toJson(requestBody.get("reportIdList")), Integer.class);
        String planId = (String) requestBody.get(ParameterKey.PLANID.getDisplay());

        OperationResult operationResult = examReportBusinessService.downloadReport(reportIdList, adminUserInfo.getAppID(), adminUserInfo.getExamSiteID(), planId);
        CommonFunction.responseWrite(response,operationResult);
    }


    //************************************************随考情况**********************************************************

    /**
     * 获取随考的考试结果列表
     * @param requestBody
     * @param request
     * @param response
     */
    @RequestMapping(value = "/GetFreeExamReportList",method = RequestMethod.POST)
    public void getFreeExamReportList(@RequestBody Map<String,Object> requestBody,HttpServletRequest request,HttpServletResponse response){
        String account = (String) requestBody.get("account");
        ExamAdminInfoDTO adminUserInfo = getAdminUserInfo(account);
        //考试计划ID
        String planId = (String) requestBody.get(ParameterKey.PLANID.getDisplay());
        //科目ID
        String subjectId = (String) requestBody.get(ParameterKey.SUBJECTID.getDisplay());
        //参数
        String parameter = (String) requestBody.get("parameter");

        //如果是汉字则为名称检索，否则为准考证号检索
        String examCardNo = null;
        String examineeName = null;

        Pattern compile = Pattern.compile("^[\\u4e00-\\u9fa5]+$");
        if(parameter != null){
            if(compile.matcher(parameter.trim()).matches()){
                examineeName = parameter.trim();
            }else{
                examCardNo = parameter.trim();
            }
        }

        List<ExamingMonitorViewModel> freeExamReportList = examReportBusinessService.findFreeExamReportList(adminUserInfo.getAppID(), planId, subjectId, adminUserInfo.getExamSiteID(), examCardNo, examineeName);
        CommonFunction.responseWrite(response,freeExamReportList);
    }

    /**
     * 分页查询计划科目结果列表
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/findFreeExamSubjectReportList",method = RequestMethod.POST)
    public void findFreeExamSubjectReportList(@RequestBody Map<String,Object> requestBody,HttpServletResponse response){
        PageBean<ExamReportDTO> freeExamSubjectReportList = examReportBusinessService.findFreeExamSubjectReportList(requestBody);
        CommonFunction.responseWrite(response,freeExamSubjectReportList);
    }

    /**
     * 获取随考的已生成列表
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/GetGeneratedList",method = RequestMethod.POST)
    public void getGeneratedList(@RequestBody Map<String,Object> requestBody,HttpServletResponse response){
        String account = (String) requestBody.get("account");
        String planId = (String) requestBody.get(ParameterKey.PLANID.getDisplay());

        List<Map<String, Object>> exitFreeReportList = examReportBusinessService.findExitFreeReportList(getAdminUserInfo(account).getAppID(), planId);
        CommonFunction.responseWrite(response,exitFreeReportList);
    }

    /**
     * 随考
     * @param requestBody
     * @param request
     * @param response 压缩包路径
     */
    @RequestMapping(value = "/FreeExamDownload",method = RequestMethod.POST)
    public void freeExamDownload(@RequestBody Map<String,Object> requestBody,HttpServletRequest request,HttpServletResponse response) throws IOException {
        String account = (String) requestBody.get("account");
        ExamAdminInfoDTO adminUserInfo = getAdminUserInfo(account);
        List<FreeExamDownloadInfo> selList = GsonUtil.fromJsonToList(GsonUtil.toJson(requestBody.get("selList")), FreeExamDownloadInfo.class);
        String planId = (String) requestBody.get(ParameterKey.PLANID.getDisplay());

        OperationResult operationResult = examReportBusinessService.freeDownloadReport(selList, adminUserInfo.getAppID(), planId, adminUserInfo.getExamSiteID());
        CommonFunction.responseWrite(response,operationResult);
    }

    /**
     *
     * @param filePath
     * @param response
     */
    @RequestMapping(value = "/Download",method = RequestMethod.POST)
    public void download(String filePath,HttpServletResponse response){
        //文件地址
        Boolean status = FileUtil.download(filePath, response);
        if(!status){
            Map<String,Object> returnMap = new HashMap<>(2);
            returnMap.put("ResultType",OperationResultType.Warning);
            returnMap.put("Message","未能找到导出文件！");
            CommonFunction.responseWrite(response,returnMap);
        }
    }

    /**
     * 上传考试计划包
     * @param requestBody
     * @param response
     */
    @RequestMapping(value = "/UploadResultPackage",method = RequestMethod.POST)
    public void uploadResultPackage(@RequestBody Map<String,Object> requestBody,HttpServletResponse response){
        Map<String,Object> paramMap = new HashMap<>();
        List<UploadExamResultDTO> examResultList = GsonUtil.fromJsonToList(GsonUtil.toJson(requestBody.get("examResultList")), UploadExamResultDTO.class);
        OperationResult operationResult;
        String batchId = examResultList.get(0).getBatchId();
        Integer deploymentMode = Integer.valueOf(examResultList.get(0).getDeploymentMode().toString());
        if(deploymentMode.equals(DeploymentMode.LAN_Deployment.getPrefix())){
            String fileBase64 = Base64Util.fileTOBase64(requestBody.get("filePath").toString());
            paramMap.put("data",fileBase64);
        }
        paramMap.put("examResultUrlList",examResultList);
        String result = HttpRequestUtils.send_UnirestRecoredSaving_post(examSiteURL, "/examplan/resultpackage/web/" + batchId + "?examResultUrl=", paramMap, null);
        if(!StringUtils.isEmpty(result)){
            ReturnData returnData = GsonUtil.fromJsonToObject(result, ReturnData.class);
            if(returnData.getSuccess()){
                examResultList.forEach(uploadExamResultDTO -> {
                    FreeExamReport freeExamReport = new FreeExamReport();
                    freeExamReport.setIfUpload(ExamResultUploadState.Uploaded.getPrefix().shortValue());
                    freeExamReport.setExamResult(uploadExamResultDTO.getExamResultUrl());
                    freeExamReport.setExamReportID(Integer.valueOf(uploadExamResultDTO.getExamReportId()));
                    examReportBusinessService.updateFreeExamReport(freeExamReport);
                });
                operationResult = new OperationResult(OperationResultType.Success,"上传成功");
            }else{
                operationResult = new OperationResult(OperationResultType.Warning,returnData.getMessage());
            }
        }else{
            operationResult = new OperationResult(OperationResultType.Warning,"上传计划包无响应！");
        }
        CommonFunction.responseWrite(response,operationResult);
    }

}
